/**
 *
 */
package com.etrans.web.gps.business.system.controller;

import java.util.Date;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.etrans.web.gps.base.controller.BaseController;
import com.etrans.web.gps.business.log.domain.LoginRecordVO;
import com.etrans.web.gps.business.log.service.LoginRecordService;
import com.etrans.web.gps.business.system.domain.SysUser;
import com.etrans.web.gps.business.system.service.UserService;
import com.etrans.web.gps.common.Constant;
import com.etrans.web.gps.common.page.ResultContans;
import com.etrans.web.gps.util.CsEncodeUtils;

/**
 * <p>Title: LoginController.java<／p>
 * <p>Description: <／p>
 * <p>Copyright: Copyright (c) 2007<／p>
 * <p>Company: E-trans<／p>
 *
 * @author R.Lao
 * @version 1.0
 * @date 2017年6月14日
 * @time 下午3:31:12
 */
/**
 * @author Administrator
 *
 */
@Controller
public class LoginController extends BaseController {

    @Autowired
    private UserService userService;

    /**
     * 日志对象
     */
    private final Logger logger = LoggerFactory.getLogger(LoginController.class);

    /**
     * 登陆跳转
     *
     * @return login String
     */
    @RequestMapping(value = "login.html")
    public String execute() {
        return "login";
    }

    /**
     * 过时登陆跳转
     *
     * @return login String
     */
    @RequestMapping(value = "relogin.html")
    public String executere(Model model) {
        return "outTime";
    }


    /**
     * 执行登陆
     *
     * @param user
     * @return
     */
    @SuppressWarnings("finally")
	@RequestMapping(value = "doLogin.html", method = RequestMethod.POST)
    public ModelAndView login(SysUser user,HttpServletRequest request) {
        ModelAndView modelAndView = null;
        try {
        	if (StringUtils.isEmpty(user.getLogin_name()) || StringUtils.isEmpty(user.getLogin_pwd())) {
        		 modelAndView = new ModelAndView("login");
                 modelAndView.getModel().put("msg", "账号或密码不能为空");
                 return modelAndView;
                 
			}
            SysUser queryUser = userService.queryByLoginName(user.getLogin_name());
            if (null != queryUser) {
                if (!queryUser.getEnable()) {
                    modelAndView = new ModelAndView("login");
                    modelAndView.getModel().put("msg", "账号已被禁用");
                    return modelAndView;
                }
                if (CsEncodeUtils.Encrypt(user.getLogin_pwd()).equals(queryUser.getLogin_pwd())) {
                	getSession().removeAttribute(Constant.USER_OP_MENU);
                    getSession().setAttribute(Constant.LOGIN_SESSION_NAME, queryUser);
                    modelAndView = new ModelAndView("redirect:/index/toIndex.html");
                    //添加登录成功日志
                    WriteLoginRecord(1,queryUser,request);
                } else {
                    modelAndView = new ModelAndView("login");
                    modelAndView.getModel().put("msg", "密码错误");
                    modelAndView.getModel().put("login_name", user.getLogin_name());
                  //添加登录失败日志
                    WriteLoginRecord(0,queryUser,request);
                }
            } else {
                modelAndView = new ModelAndView("login");
                modelAndView.getModel().put("msg", "账号错误");
	            //账号不存在时不写入日志，防止报空指针错误
              
            }
        } catch (Exception e) {
            if (modelAndView == null)
                modelAndView = new ModelAndView("login");
            logger.error(e.getMessage());
            e.printStackTrace();
        } finally {
            return modelAndView;
        }
    }

    /**
     * 注销登陆
     *
     * @return login String
     */
    @RequestMapping("loginOut.html")
    public ModelAndView loginOut() {
    	getSession().removeAttribute(Constant.USER_OP_MENU);
        getSession().removeAttribute(Constant.LOGIN_SESSION_NAME);
        ModelAndView modelAndView = new ModelAndView("redirect:login.html");
        return modelAndView;
    }


    /**
     * @return login String
     */
    @ResponseBody
    @RequestMapping(value = "updatePassword.html", method = RequestMethod.POST)
    public HashMap<String, Object> updatePassword(@RequestParam String newPwd,
                                                  @RequestParam String confirm,
                                                  @RequestParam String oldPwd) {
        HashMap<String, Object> result = new HashMap<>();
        if (null == newPwd) {
            result.put("code", ResultContans.RETURN_ERROR_CODE);
            result.put("msg", "初始密码不能为空");
            return result;
        }
        if (null == confirm) {
            result.put("code", ResultContans.RETURN_ERROR_CODE);
            result.put("msg", "密码确认不能为空");
            return result;
        }
        if (null == oldPwd) {
            result.put("code", ResultContans.RETURN_ERROR_CODE);
            result.put("msg", "旧密码不能为空");
            return result;
        }
        if (!confirm.equals(newPwd)) {
            result.put("code", ResultContans.RETURN_ERROR_CODE);
            result.put("msg", "两次密码不匹配");
            return result;
        }
        try {
            SysUser user = getSysUser();
            HashMap<String, Object> params = new HashMap<>();
            params.put("login_pwd", CsEncodeUtils.Encrypt(newPwd));
            params.put("old_pwd", CsEncodeUtils.Encrypt(oldPwd));
            params.put("userId", user.getId());
            SysUser sysUser = userService.queryUserByPwd(params);
            if (sysUser != null) {
                userService.updatePassword(params);
                result.put("code", ResultContans.RETURN_OK_CODE);
                result.put("msg", "密码修改成功");
                return result;
            } else {
                result.put("code", ResultContans.RETURN_ERROR_CODE);
                result.put("msg", "旧密码错误");
                return result;
            }
        } catch (Exception e) {
            logger.error("{}", e.getMessage());
            result.put("code", ResultContans.RETURN_ERROR_CODE);
            result.put("msg", "运行错误");
            return result;
        }
    }
    /**
     * 写入登录日志
     * @param queryUser
     */
    public void WriteLoginRecord(int isSuccess,SysUser user,HttpServletRequest request) {
    	//创建Java类
    	LoginRecordVO loginRecordVO = new LoginRecordVO();
        loginRecordVO.setUserId(user.getId());
        loginRecordVO.setLogin_name(user.getLogin_name());
        loginRecordVO.setUser_name(user.getUser_name());
        loginRecordVO.setRole_name(user.getRole_name());
        loginRecordVO.setLoginIP(getIp(request));
        loginRecordVO.setLoginTime(new Date());
        loginRecordVO.setLoginAddress("贵州贵阳");
        loginRecordVO.setArea_name(user.getArea_name());
        loginRecordVO.setIsSuccess(isSuccess);
        LoginRecordService loginRecordService = new LoginRecordService();
        loginRecordService.insertLoginRecord(loginRecordVO);
    }
    /**
     * 获取登录用户IP
     * @param request
     * @return
     */
    public static String getIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if(null != ip && !"unKnown".equalsIgnoreCase(ip)){
             //多次反向代理后会有多个ip值，第一个ip才是真实ip
            int index = ip.indexOf(",");
           if(index != -1){
                return ip.substring(0,index);
            }else{
                return ip;
            }
        }
        ip = request.getHeader("X-Real-IP");
        if(null != ip  && !"unKnown".equalsIgnoreCase(ip)){
            return ip;
        }
        return request.getRemoteAddr();
    }
}
